import React, { Component } from "react";
import { Button, message, Popconfirm, Modal } from "antd";
import "./ExamPaper.less";
import ShowSingleChoice from "@/components/Question/Show/ShowSingleChoice";
import ShowMultipleChoice from "@/components/Question/Show/ShowMultipleChoice";
import ShowFillInBlank from "@/components/Question/Show/ShowFillInBlank";
import { getCookie } from "@/utils/cookie/cookie";
import {
    getQuestionListByExamPaperId,
    submitAnswer,
    getStuAnswerByExamId
} from '@/services/exam'
import { connect } from "dva"
import moment from "moment";

const mapDispatchToProps = (dispatch) => {
    return {
        changeExamListTabTeach(examListTab) {
            dispatch({
                type: `teacher/changeState`,
                result: { data: examListTab },
                field: "examListTab",
            });
        },
        changeExamListTabStu(examListTab) {
            dispatch({
                type: `student/changeState`,
                result: { data: examListTab },
                field: "examListTab",
            });
        },
    }
}
let stuAnswerList = []
let type = ""
let surplusDuration = 0;
let timer = null
let firstTip = true
class Index extends Component {

    constructor(props) {
        super(props)
        this.state = {
            questionList: [],
            submitLoading: false,
            stuAnswerList: [],
            timeOutTipModal: false
        }
        type = props.type
    }

    componentDidMount() {
        (async () => {
            if (this.props.showSubmitBtn) {
                const endTime = moment(this.props.info?.endTime, "YYYY-MM-DD HH:mm:ss")
                const nowTime = moment()
                if (endTime.isValid()) {
                    surplusDuration = (endTime - nowTime) / 1000
                } else {
                    surplusDuration = 0
                }
                timer = setInterval(() => {
                    surplusDuration -= 1
                    console.log(surplusDuration);
                    if (surplusDuration <= 0) {
                        this.setState({
                            timeOutTipModal: true
                        })
                        clearInterval(timer);
                    } else if (surplusDuration <= 10 * 60 && firstTip) {
                        const m = parseInt(surplusDuration / 60, 10)
                        let content = `还有${m}分钟考试结束，请尽快作答`
                        if (m <= 0) {
                            content = `还有不到1分钟考试结束，请尽快提交试卷`
                        }
                        message.warn({
                            key: "timeTip",
                            content,
                            onClick: () => {
                                message.destroy("timeTip")
                            },
                            duration: 0
                        })
                        firstTip = false
                    }
                }, 1000)
            }
            if (this.props.type === "checkPaper") {
                let result2 = null
                if (this.props.type2 === "teacherCheckStudent") {
                    result2 = await getStuAnswerByExamId({
                        stu_id: this.props.info.stu_id,
                        exam_id: this.props.info?.key
                    })
                } else {
                    result2 = await getStuAnswerByExamId({
                        stu_id: getCookie("userId"),
                        exam_id: this.props.info?.key
                    })
                }
                if (result2.status === 0 && result2.data) {
                    const { answer_list } = result2.data
                    this.setState({
                        stuAnswerList: answer_list.split("-$$&&$$-").map((answer) => {
                            return answer.split("-&&-")
                        })
                    })
                }
            }
            const result = await getQuestionListByExamPaperId({ exam_paper_id: this.props.examPaperId })
            if (result.status === 0) {
                this.setState({
                    questionList: result.data.map((data, index) => {
                        let trueAnswer = data?.true_answer?.split("-$$&&$$-")
                        if (trueAnswer instanceof Array && data?.question_type !== "fillInBlank") {
                            trueAnswer.sort((a, b) => {
                                return a > b ? 1 : -1
                            })
                        }
                        let studentAnswer = this.state.stuAnswerList[index]
                        if (studentAnswer instanceof Array && data?.question_type !== "fillInBlank") {
                            studentAnswer.sort((a, b) => {
                                return a > b ? 1 : -1
                            })
                        }
                        return {
                            type: data?.question_type,
                            score: data?.score,
                            question: data?.question_context,
                            options: data?.options?.split("-$$&&$$-"),
                            trueAnswer: trueAnswer.join('、'),
                            studentAnswer: studentAnswer?.join?.("、") || undefined
                        }
                    })
                })
                stuAnswerList = result.data.map((_, index) => {
                    return {
                        questionId: index + 1,
                        stuAnswer: undefined,
                        type: undefined
                    }
                })
                this.props.getStuAnswerList?.(stuAnswerList)
            } else {
                message.error({
                    key: 'tip',
                    content: '加载失败',
                    duration: 1
                })
            }
        })();
    }

    componentWillUnmount() {
        if (timer) {
            clearInterval(timer)
        }
    }

    async submit(status) {
        this.setState({
            submitLoading: true
        })
        const answer_paper_id = `${new Date().getTime()}`
        let answer_paper = {
            answer_paper_id,
            answer_list: stuAnswerList.map((answer) => {
                let answerStr = ""
                if (answer.stuAnswer) {
                    if (answer.stuAnswer instanceof Array) {
                        answerStr = answer.stuAnswer.join("-&&-")
                    } else {
                        answerStr = `${answer.stuAnswer}`
                    }
                } else {
                    answerStr = ""
                }
                return answerStr
            }).join("-$$&&$$-")
        }
        let score_paper = {
            score_paper_id: `${new Date().getTime()}`,
            stu_id: getCookie("userId"),
            exam_id: this.props.info.key,
            exam_paper_id: this.props.info.examPaperId,
            answer_paper_id,
            max_score: this.props.info.maxScore,
            pass_score: this.props.info.passScore,
            status,
        }
        const result = await submitAnswer({ score_paper, answer_paper })
        if (result.status === 0) {
            message.success("提交成功")
            if (getCookie("identity") === "student") {
                this.props.changeExamListTabStu()
            } else {
                this.props.changeExamListTabTeach()
            }
        } else {
            message.error("提交失败")
        }
        this.setState({
            submitLoading: true
        })
    }

    render() {
        if (this.props.examPaperId) {
            console.log(this.props)
            const { showTrueAnswer, showStudentAnswer, getStuAnswerList, showSubmitBtn } = this.props
            const { questionList } = this.state
            return (
                <div className="exam-paper">
                    <div style={{ width: "100%", border: "1px #e0e0e0 solid", borderRadius: "16px", backgroundColor: "#e0e0e0", marginBottom: "8px" }}>
                        {questionList?.map?.((question, index) => {
                            if (question.type === 'singleChoice') {
                                return <ShowSingleChoice
                                    key={`Q${index + 1}`}
                                    className={`Q${index + 1}`}
                                    index={index + 1}
                                    showTrueAnswer={showTrueAnswer}
                                    showStudentAnswer={showStudentAnswer}
                                    onChange={(answer) => {
                                        stuAnswerList[index].stuAnswer = answer
                                        stuAnswerList[index].type = "selected"
                                        getStuAnswerList?.(stuAnswerList)
                                    }}
                                    {...question} />
                            }
                            if (question.type === 'multipleChoice') {
                                return <ShowMultipleChoice
                                    key={`Q${index + 1}`}
                                    className={`Q${index + 1}`}
                                    index={index + 1}
                                    showTrueAnswer={showTrueAnswer}
                                    showStudentAnswer={showStudentAnswer}
                                    onChange={(answer) => {
                                        stuAnswerList[index].stuAnswer = answer
                                        if (answer instanceof Array && answer.length > 0) {
                                            stuAnswerList[index].type = "selected"
                                        } else {
                                            stuAnswerList[index].type = undefined
                                        }
                                        getStuAnswerList?.(stuAnswerList)
                                    }}
                                    {...question} />
                            }
                            if (question.type === 'fillInBlank') {
                                return <ShowFillInBlank
                                    key={`Q${index + 1}`}
                                    className={`Q${index + 1}`}
                                    index={index + 1}
                                    showTrueAnswer={showTrueAnswer}
                                    showStudentAnswer={showStudentAnswer}
                                    onChange={(answer) => {
                                        stuAnswerList[index].stuAnswer = answer
                                        stuAnswerList[index].type = "selected"
                                        getStuAnswerList?.(stuAnswerList)
                                    }}
                                    {...question} />
                            }
                            return null
                        })}
                        <div style={{
                            width: "100%",
                            height: '80px',
                            display: showSubmitBtn ? 'flex' : 'none',
                            justifyContent: 'center',
                            alignItems: 'center'
                        }}>
                            <Popconfirm
                                title={(() => {
                                    const str1 = "确定提交吗?"
                                    let flag = 0
                                    stuAnswerList.forEach((answer) => {
                                        if (answer.type !== "selected") {
                                            console.log(answer.type)
                                            flag += 1
                                        }
                                    })
                                    if (flag > 0) {
                                        return `${str1}你还有${flag}道题未完成作答`
                                    } else {
                                        return str1
                                    }
                                })()}
                                onConfirm={() => {
                                    this.submit("normal")
                                }}
                                onCancel={() => {
                                    this.setState({
                                        beforeSubmitModal: false
                                    })
                                }}>
                                <Button type='primary' style={{
                                    width: "50%",
                                    height: '50px'
                                }} loading={this.state.submitLoading}>提交答卷</Button>
                            </Popconfirm>
                        </div>
                        <Modal title="警告" visible={this.state.timeOutTipModal} onOk={() => {
                            this.submit("overtime")
                        }}>
                            <span>
                                已到考试结束时间，请提交试卷，如果退出页面将无法再次提交！
                            </span>
                        </Modal>
                    </div>
                </div>
            );
        } else {
            if (getCookie("identity") === "student") {
                this.props.changeExamListTabStu()
            } else {
                this.props.changeExamListTabTeach()
            }
            return ""
        }
    }
}

export default connect(null, mapDispatchToProps)(Index);
